<template>
  <view class="container">
    <view class="avatar-section">
      <view class="preview-box">
        <image :src="avatarUrl || '/static/img/default-avatar.png'" class="avatar-preview" mode="aspectFill"></image>
        <view class="loading-overlay" v-if="uploading">
          <view class="progress-text">{{uploadProgress}}%</view>
        </view>
      </view>
      
      <view class="upload-buttons">
        <button class="select-btn" @click="chooseImage">选择图片</button>
        <button class="upload-btn" @click="uploadAvatar" :disabled="!tempFilePath || uploading">上传头像</button>
      </view>
      
      <view class="tips">
        <text>提示：</text>
        <text>1. 请选择清晰的正面照片</text>
        <text>2. 支持JPG、PNG格式图片</text>
        <text>3. 图片大小不超过2MB</text>
      </view>
    </view>
  </view>
</template>

<script>
  import { uploadAvatar } from '@/api/member.js';
  import { mapMutations } from 'vuex';
  import { API_BASE_URL } from '@/utils/appConfig.js';
  import { uploadFileToMinio } from '@/utils/minioUtil.js';
  
  export default {
    data() {
      return {
        avatarUrl: '',       // 当前头像URL
        tempFilePath: '',    // 临时文件路径
        uploading: false,    // 上传状态
        uploadProgress: 0,   // 上传进度
        maxSize: 2 * 1024 * 1024, // 最大2MB
      }
    },
    onLoad() {
      // 获取当前用户信息中的头像
      const userInfo = this.$store.state.userInfo;
      if (userInfo && userInfo.icon) {
        this.avatarUrl = userInfo.icon;
      }
    },
    methods: {
      ...mapMutations(['updateUserInfo']),
      
      // 选择图片
      chooseImage() {
        uni.chooseImage({
          count: 1, // 限制为1张
          sizeType: ['compressed'], // 压缩图片
          sourceType: ['album', 'camera'], // 从相册或相机选择
          success: (res) => {
            const tempFile = res.tempFiles[0];
            
            // 检查文件大小
            if (tempFile.size > this.maxSize) {
              uni.showToast({
                title: '图片大小不能超过2MB',
                icon: 'none'
              });
              return;
            }
            
            this.tempFilePath = res.tempFilePaths[0];
            // 预览选择的图片
            this.avatarUrl = this.tempFilePath;
            
            // 可以选择裁剪图片
            this.cropImage();
          }
        });
      },
      
      // 裁剪图片 - uni-app在部分平台支持图片裁剪功能
      cropImage() {
        // 检查平台是否支持裁剪
        // #ifdef APP-PLUS || MP-WEIXIN
        uni.navigateTo({
          url: `/pages/common/cropper?src=${this.tempFilePath}`,
          events: {
            // 获取裁剪后的图片
            cropImage: (data) => {
              if (data.tempFilePath) {
                this.tempFilePath = data.tempFilePath;
                this.avatarUrl = this.tempFilePath;
              }
            }
          }
        });
        // #endif
      },
      
      // 上传头像
      uploadAvatar() {
        if (!this.tempFilePath) {
          uni.showToast({
            title: '请先选择图片',
            icon: 'none'
          });
          return;
        }
        
        this.uploading = true;
        this.uploadProgress = 0;
        
        // 显示上传中提示
        uni.showLoading({
          title: '上传中...'
        });
        
        // 使用MinIO工具类上传文件
        uploadFileToMinio(this.tempFilePath, (progress) => {
          this.uploadProgress = progress;
        }).then(result => {
          console.log('MinIO上传成功:', result);
          // MinIO返回格式：{ url: 'http://...', name: '文件名.png' }
          const imageUrl = result.url; // 获取MinIO返回的图片URL
          
          uni.showToast({
            title: '头像上传成功',
            icon: 'success'
          });
          
          // 更新用户头像信息到后端服务
          this.updateAvatarInfo(imageUrl);
        }).catch(error => {
          console.error('上传失败:', error);
          uni.showToast({
            title: error.message || '上传失败，请重试',
            icon: 'none'
          });
        }).finally(() => {
          uni.hideLoading();
          this.uploading = false;
        });
      },
      
      // 将MinIO返回的图片URL更新到用户资料
      updateAvatarInfo(imageUrl) {
        console.log('准备更新头像URL:', imageUrl);
        // 调用API更新用户头像URL
        uploadAvatar(imageUrl).then(response => {
          console.log('头像更新响应:', response);
          if (response.code === 200) {
            // 更新Vuex中的用户头像信息
            this.updateUserInfo({
              icon: imageUrl
            });
            
            // 延迟返回上一页
            setTimeout(() => {
              uni.navigateBack();
            }, 1500);
          } else {
            uni.showToast({
              title: response.message || '头像信息更新失败',
              icon: 'none'
            });
          }
        }).catch(error => {
          console.error('更新头像信息失败:', error);
          uni.showToast({
            title: '更新头像信息失败，请重试',
            icon: 'none'
          });
        });
      }
    }
  }
</script>

<style lang="scss">
  .container {
    padding: 40rpx;
    min-height: 100vh;
    background-color: #f8f8f8;
  }
  
  .avatar-section {
    display: flex;
    flex-direction: column;
    align-items: center;
    
    .preview-box {
      width: 300rpx;
      height: 300rpx;
      margin: 40rpx 0;
      border-radius: 50%;
      overflow: hidden;
      box-shadow: 0 0 20rpx rgba(0,0,0,0.1);
      background-color: #fff;
      position: relative;
      
      .avatar-preview {
        width: 100%;
        height: 100%;
      }
      
      .loading-overlay {
        position: absolute;
        top: 0;
        left: 0;
        width: 100%;
        height: 100%;
        background-color: rgba(0,0,0,0.5);
        display: flex;
        align-items: center;
        justify-content: center;
        
        .progress-text {
          color: #fff;
          font-size: 36rpx;
          font-weight: bold;
        }
      }
    }
    
    .upload-buttons {
      width: 100%;
      display: flex;
      flex-direction: column;
      margin-bottom: 40rpx;
      
      .select-btn, .upload-btn {
        width: 80%;
        height: 80rpx;
        line-height: 80rpx;
        margin: 20rpx auto;
        font-size: 28rpx;
        border-radius: 40rpx;
      }
      
      .select-btn {
        background-color: #fff;
        color: $font-color-dark;
        border: 1px solid #ddd;
      }
      
      .upload-btn {
        background-color: $uni-color-primary;
        color: #fff;
        
        &[disabled] {
          background-color: #f5f5f5;
          color: #999;
        }
      }
    }
    
    .tips {
      margin-top: 20rpx;
      font-size: 24rpx;
      color: $font-color-light;
      text-align: center;
      display: flex;
      flex-direction: column;
    }
  }
</style> 